package com.gu.myviewmodel.ui.homepage.model

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import com.gu.myviewmodel.app.log
import com.gu.myviewmodel.repo.Repo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import javax.inject.Inject

@HiltViewModel
class MainViewModel @Inject constructor(private val repo: Repo) : ViewModel() {

    val loading = MutableLiveData(false)

    val loadAction = MutableStateFlow(LoadType.IDLE)

    private val dataFlow = flow<Result<*>> {
        log("repo=$repo")
        loading.value = true
        val res = repo.loadData()
        emit(Result.success(res))
        loading.value = false
    }.catch { cause ->
        loading.value = false
        emit(Result.failure<Any>(Throwable("error is :" + cause.message)))
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    val data = loadAction.filter { it != LoadType.IDLE }.flatMapLatest { type ->
        if (type == LoadType.REFRESH) {
            repo.changeRefreshFlag()
        }
        dataFlow
    }.asLiveData()

    private fun findTag() = "MainViewModel"

    private fun log(str: String) {
        log(findTag(), str)
    }

    enum class LoadType {
        IDLE, INIT, REFRESH
    }
}

